<?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Yansongda\Pay\Pay;

class WeChatController extends Controller
{
    protected $client;
    protected $miniapp_id;
    protected $app_secret;
    protected $mch_id;
    protected $key;
    protected $wechat;

    public function __construct(){
        $this->client = new Client();
        $this->miniapp_id = Config('wechat')['miniapp_id'];
        $this->app_secret = Config('wechat')['app_secret'];
        $this->mch_id = Config('wechat')['mch_id'];
        $this->key = Config('wechat')['key'];
        $config = $config = [
            'miniapp_id' => $this->miniapp_id, // 小程序 APPID
            'mch_id' => $this->mch_id,
            'key' => $this->key,
            'notify_url' => '',//单独的业务控制
            'cert_client' => storage_path('wechat/cert/apiclient_cert.pem'), // optional, 退款，红包等情况时需要用到
            'cert_key' => storage_path('wechat/cert/apiclient_key.pem'),// optional, 退款，红包等情况时需要用到
            'log' => [ // optional
                'file' => storage_path('wechat/wechat.log'),
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
                // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
            ],
            // 'mode' => 'dev',
        ];
        $this->wechat = Pay::wechat($config);
    }

    public function getAccessToken(){
        $filepath = storage_path('wechat/access_token.txt');
        if(file_exists($filepath)){
            $f = fopen($filepath,'r');
            $data = json_decode(fread($f,filesize($filepath)),true);
            fclose($f);
            if(time() < $data['expires_at']){
                //1.只有当文件存在且口令没有过期才返回
                return $data['access_token'];
            }
        }
        //2.否则重写这个文件
        $f = fopen($filepath,'w+');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->miniapp_id}&secret={$this->app_secret}";
        $res = $this->client->request('GET', $url);
        fwrite($f, json_encode([
            'access_token' => json_decode($res->getBody(),true)['access_token'],
            'expires_at' => time() + json_decode($res->getBody(),true)['expires_in']
        ]));
        fclose($f);
        return json_decode($res->getBody(),true)['access_token'];

    }

    public function getOpenid(Request $request){
        $code = $request->filled('code') ? $request->code : NULL;
        if($code){
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->miniapp_id}&secret={$this->app_secret}&js_code={$code}&grant_type=authorization_code";
            $res = json_decode($this->client->request('GET', $url)->getBody(),true);
            if(!isset($res['errcode'])){
                return json_encode([
                    'code' => 1,
                    'msg' => 'success',
                    'openid' => $res['openid']
                ]);
            }else{
                return json_encode([
                    'code' => $res['errcode'],
                    'msg' => $res['errmsg']
                ]);
            }
        }else{
            return json_encode([
                'code' => -1,
                'msg' => 'code 不能为空'
            ]);
        }
    }

    //小程序支付
    public function miniappPay($order){
        return $this->wechat->miniapp($order);
    }

    public function refund($order){

    }

    //=======================
    //       [模版消息]
    //=======================
    const PAYMENT_SUCCESS = 'W7wEL6spMcejDVXGbnHvFL-9AHBVsXDF7cNSCCCIyD0';//订单支付成功通知
    const CONSIGN_SUCCESS = 'raIJJUF45-MnjV0CDazxFRYSCpnyBRPQUKbtG_BM4Cw';//发货成功提醒

    public function sendTemplateMessage($data){
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;
        $res = $this->client->request('POST', $url, ['json'=>$data]);
        Log::debug($res);
    }

    /**
     * 订单支付成功通知
     * @param string $openid
     * @param  $keyword1 订单编号
     * @param  $keyword2 商品名称
     * @param  $keyword3 支付金额
     * @param  $keyword4 支付时间
     * @param string $page
     * @param string $form_id
     */
    public function Message_payment_success($openid,$keyword1,$keyword2,$keyword3,$keyword4,$page='',$form_id=''){
        $this->sendTemplateMessage([
            'touser' => $openid,
            'template_id' => self::PAYMENT_SUCCESS,
            'page' => $page,
            'form_id' => $form_id,
            'data' => [
                'keywords1' => ['value'=>$keyword1],
                'keywords2' => ['value'=>$keyword2],
                'keywords3' => ['value'=>$keyword3],
                'keywords4' => ['value'=>$keyword4],
            ]
        ]);
    }

    /**
     * 发货成功提醒
     * @param string $openid
     * @param  $keyword1 物品名称
     * @param  $keyword2 快递公司
     * @param  $keyword3 快递单号
     * @param  $keyword4 收货地址
     * @param  $keyword5 发货时间
     * @param string $page
     * @param string $form_id
     */
    public function Message_consign_success($openid,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5,$page='',$form_id=''){
        $this->sendTemplateMessage([
            'touser' => $openid,
            'template_id' => self::CONSIGN_SUCCESS,
            'page' => $page,
            'form_id' => $form_id,
            'data' => [
                'keywords1' => ['value'=>$keyword1],
                'keywords2' => ['value'=>$keyword2],
                'keywords3' => ['value'=>$keyword3],
                'keywords4' => ['value'=>$keyword4],
                'keywords5' => ['value'=>$keyword5],
            ]
        ]);
    }
}
